let canvas_config ={
  background_color: "rgb(239, 247,254)",
}

function dataURLToBlob(dataurl) {
  let arr = dataurl.split(',');
  let mime = arr[0].match(/:(.*?);/)[1];
  let bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {type: mime});
}


function CanvasDraw(canvas) {
  if(canvas===null||canvas===undefined) return this;
  this.canvas = canvas;
  this.ctx = this.canvas.getContext('2d');
  this.width = this.canvas.offsetWidth;
  this.height = this.canvas.offsetHeight;
  this.init();
}

CanvasDraw.prototype.init = function () {
  this.ctx.fillStyle = canvas_config.background_color;
  this.ctx.fillRect(0, 0, this.canvas.offsetWidth, this.canvas.offsetHeight);
}

CanvasDraw.prototype.getLeftCenterWidth = function (obj) {
  return (this.canvas.width-obj.width)/2;
}

CanvasDraw.prototype.color = function (color) {
  this.ctx.fillStyle =color;
}

CanvasDraw.prototype.drawImage = function (img,y) {
  let x = (this.width - img.width) / 2;
  this.ctx.drawImage(img, x, y, img.width, img.height);
}


CanvasDraw.prototype.download=function() {
  let a = document.createElement('a');
  let blob = dataURLToBlob(this.canvas.toDataURL('image/png'));
  a.setAttribute('href', URL.createObjectURL(blob));
  a.setAttribute('download', 'canvas.png');
  a.click();
  URL.revokeObjectURL(blob);
}

CanvasDraw.prototype.download_canvas=function(canvas) {
  let a = document.createElement('a');
  let blob = dataURLToBlob(canvas.toDataURL('image/png'));
  a.setAttribute('href', URL.createObjectURL(blob));
  a.setAttribute('download', 'canvas.png');
  a.click();
  URL.revokeObjectURL(blob);
}

CanvasDraw.prototype.drawText=function(obj) {
  if(obj.color)  this.color(obj.color);
  this.ctx.font = obj.font;
  this.ctx.fillText(obj.text,obj.x,obj.y);
}

CanvasDraw.prototype.drawRoundRect = function (obj,r) {
  if(obj.color)  this.color(obj.color);
  if (obj.width < 2 * r) {r =obj.width / 2;}
  if (obj.height < 2 * r){ r = obj.height / 2;}
  this.ctx.beginPath();
  this.ctx.moveTo(obj.x+r, obj.y);
  this.ctx.arcTo(obj.x+obj.width, obj.y, obj.x+obj.width, obj.y+obj.height, r);
  this.ctx.arcTo(obj.x+obj.width, obj.y+obj.height, obj.x, obj.y+obj.height, r);
  this.ctx.arcTo(obj.x, obj.y+obj.height, obj.x, obj.y, r);
  this.ctx.arcTo(obj.x, obj.y, obj.x+obj.width, obj.y, r);
  this.ctx.closePath();
  this.ctx.fill();
}

export default CanvasDraw
